package com.wangcanxuan.www.service.Impl;


import com.wangcanxuan.www.dao.mapper.ApplyMapper;
import com.wangcanxuan.www.dao.mapper.TribeMapper;
import com.wangcanxuan.www.dao.mapper.UserMapper;

import com.wangcanxuan.www.entity.dto.ResultInfo;
import com.wangcanxuan.www.entity.po.Apply;
import com.wangcanxuan.www.entity.po.Tribe;
import com.wangcanxuan.www.entity.po.User;
import com.wangcanxuan.www.exception.ServiceException;
import com.wangcanxuan.www.proxy.DaoProxy;
import com.wangcanxuan.www.service.ApplyService;
import com.wangcanxuan.www.util.SecurityUtil;
import com.wangcanxuan.www.util.ValidateUtil;

import java.util.ArrayList;
import java.util.List;

import static com.wangcanxuan.www.entity.dto.ResultConstants.SUCCESS_REQUEST_CODE;
import static com.wangcanxuan.www.service.constant.ServiceConstants.MEMBER_ID;

/**
 * 申请业务实现类
 *
 * @author HHLJ
 * @date 2022/04/06
 */
public class ApplyServiceImpl implements ApplyService {

    private final UserMapper USER_MAPPER = DaoProxy.getMapper(UserMapper.class);
    private final TribeMapper TRIBE_MAPPER = DaoProxy.getMapper(TribeMapper.class);
    private final ApplyMapper APPLY_MAPPER = DaoProxy.getMapper(ApplyMapper.class);

    @Override
    public ResultInfo<String> applyTribe(User user, String tribeName) {
        // 判断当前用户是否加入部落
        if (!ValidateUtil.strIsNullOrEmpty(user.getTribeId())) {
            return ResultInfo.operateRejectWithMessage("已加入部落！");
        }

        if (user.getExitTribeDate() == null) {
            // 设置退出时间为24小时前，更新用户
            user.setExitTribeDate(SecurityUtil.yesterdayDateTime());
            int update = USER_MAPPER.update(user);
            if (update != 1) {
                throw new ServiceException("申请部落功能异常！");
            }
            USER_MAPPER.selectById(new User(user.getId()));
        }
        // 判断退出部落的时间是否超过一天
        if (SecurityUtil.isLessThanOneDay(user.getExitTribeDate())) {
            return ResultInfo.operateRejectWithMessage("退出部落一天内不得加入任何部落！");
        }
        // 查询当前部落信息
        Tribe selectTribe = TRIBE_MAPPER.selectOneByFields(new Tribe(tribeName));
        // 插入申请到数据库
        Apply apply = new Apply(user.getId(), selectTribe.getId());
        apply = APPLY_MAPPER.selectOneByFields(apply);

        //判断数据中是否有该申请
        if (apply != null) {
            // 判断当前申请状态为空或者当前申请状态不为1时，返回拒绝信息
            if (apply.getStatus() == null || apply.getStatus() == 1) {
                return ResultInfo.operateRejectWithMessage("已申请该部落,不可以重复申请！");
            }
        }
        // 插入通知到数据库中
        apply = new Apply(user.getId(), selectTribe.getId());
        apply.setId(SecurityUtil.uuidCreateId());
        int insert = APPLY_MAPPER.insert(apply);

        if (insert != 1) {
            throw new ServiceException("申请部落功能异常！");
        }

        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());
    }

    @Override
    public ResultInfo<List<User>> selectApplyListByTribeId(String tribeId, int pageCount) {
        // 通过部落id和当前页面查询审核列表
        List<Apply> applies = APPLY_MAPPER.selectApplyListByTribeId(tribeId, pageCount);
        // 判断集合为空且页码为0，返回无审核用户的拒绝信息
        if (applies.size() == 0 && pageCount == 0) {
            return ResultInfo.operateRejectWithMessage("当前无可审核用户！");
        }
        // 判断集合为空时，返回没有下一页的拒绝信息
        if (applies.size() == 0) {
            return ResultInfo.operateRejectWithMessage("这是尾页！");
        }
        // 设置用户集合
        List<User> users = new ArrayList<>();
        // 遍历审核列表集合，通过申请人的id获取用户，添加到用户集合
        for (Apply selectApply : applies) {
            String applicantId = selectApply.getApplicantId();
            User user = new User(applicantId);
            user = USER_MAPPER.selectById(user);
            users.add(user);
        }
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(),users);
    }

    @Override
    public ResultInfo<Boolean> solveApply(String chooseUserName, User auditorUser, int status) {
        // 获取审核的用户的信息
        User user = new User();
        user.setNickName(chooseUserName);
        user = USER_MAPPER.selectOneByFields(user);

        // 获取审核用户的审核内容
        Apply selectApply = new Apply();
        selectApply.setApplicantId(user.getId());
        selectApply.setApplyingTribeId(auditorUser.getTribeId());
        Apply apply = APPLY_MAPPER.selectOneByFields(selectApply);

        // 更新审批人和申请状态
        apply.setAuditorId(auditorUser.getId());
        apply.setStatus(status);
        int update = APPLY_MAPPER.update(apply);
        if (update != 1) {
            throw new ServiceException("处理申请功能异常！");
        }

        // 创建部落部落对象，设置部落id
        Tribe tribe = new Tribe();
        tribe.setId(auditorUser.getTribeId());

        // 通过接收的status，判断该用户被接受或者拒绝
        if (status == 0) {
            // 创建部落申请拒绝通知
            NoticeServiceImpl.setNoticeForUser(user, "部落申请", "尊敬的" + chooseUserName
                    + "用户，您已被拒绝进入" + tribe.getTribeName() + "部落");

            return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(),false);
        } else {
            // 更新部落金币数
            tribe = TRIBE_MAPPER.selectById(tribe);
            tribe.setCoins(tribe.getCoins() + user.getCoins());
            int update1 = TRIBE_MAPPER.update(tribe);
            if (update1 != 1) {
                throw new ServiceException("处理申请功能异常！");
            }

            // 审核用户更新部落id，金币数
            user.setTribeId(auditorUser.getTribeId());
            user.setCoins(0);
            user.setRoleId(MEMBER_ID);
            int update2 = USER_MAPPER.update(user);
            if (update2 != 1) {
                throw new ServiceException("处理申请功能异常！");
            }

            // 删除审核用户其他的部落申请
            Apply deleteApply = APPLY_MAPPER.selectOneByFields(new Apply(user.getId()));
            if (deleteApply.getStatus() != 1) {
                APPLY_MAPPER.deleteOtherApplyByApplicantId(new Apply(user.getId()));
            }

            // 创建部落申请同意通知
            NoticeServiceImpl.setNoticeForUser(user, "部落申请", "尊敬的" + chooseUserName
                    + "用户，您已被同意进入" + tribe.getTribeName() + "部落");
            return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(),true);
        }
    }
}
